package com.netease.nimlib.ipc.cp.client;

import android.content.Context;
import android.database.ContentObserver;
import android.net.Uri;

import com.netease.nimlib.ipc.cp.protocol.Protocol;
import com.netease.nimlib.ipc.cp.client.IContentObserver;
import com.netease.nimlib.ipc.cp.client.ProviderClient;

/**
 * 数据源观察者
 *
 * Created by huangjun on 2017/11/14.
 */

public class ProviderObserver extends ContentObserver {

    private IContentObserver observer;

    private final Context context;
    private final String name;
    private final String key;
    private final int type;

    public ProviderObserver(final Context context, final String name, String key, int type, IContentObserver observer) {
        super(null);
        this.context = context;
        this.name = name;
        this.key = key;
        this.type = type;
        this.observer = observer;
    }

    @Override
    public void onChange(boolean selfChange, Uri uri) {
        super.onChange(selfChange, uri);

        if (observer != null) {
            ProviderClient client = ProviderClient.get(context, name);
            Object obj = null;
            try {
                switch (type) {
                    case Protocol.URI_TYPE_STRING:
                        obj = client.queryString(key, null);
                        break;
                    case Protocol.URI_TYPE_BOOLEAN:
                        obj = client.queryBoolean(key, false);
                        break;
                    case Protocol.URI_TYPE_INT:
                        obj = client.queryFloat(key, 0);
                        break;
                    case Protocol.URI_TYPE_LONG:
                        obj = client.queryLong(key, 0);
                        break;
                    case Protocol.URI_TYPE_FLOAT:
                        obj = client.queryFloat(key, 0.0f);
                        break;
                    default:
                        break;
                }
            } catch (Throwable th) {
                th.printStackTrace();
            }

            if (obj != null) {
                observer.onChange(name, key, type, obj);
            }
        }
    }
}
